let maxZIndex = 0
export default class TabManager {
  constructor () {
    this.list = []
  }

  restoreTabs () {
    this.list.forEach(i => {
      if (i.zIndex === maxZIndex && i.status !== 'hide') {
        i.status = 'active'
      } else if (i.status === 'active') {
        i.status = 'hungUp'
      }
    })
    // 触发vue强制更新
    this.list.push({})
    this.list.pop()
  }

  isExist (Tab) {
    return this.list.indexOf(Tab) > -1
  }

  addTab (Tab) {
    // 判断tab是否已经存在，若不存在则删除，然后新增
    const list = this.list.filter(i => i.appKey === Tab.appKey && i.name === Tab.name)
    if (list.length > 0) {
      this.removeTab(list[0])
    }
    this.newTab(Tab)
  }

  newTab (Tab) {
    // zIndex=1;maxZIndex=1;
    Tab.zIndex = ++maxZIndex
    Tab.setContainer(this)
    this.list.push(Tab)
    this.restoreTabs()
  }

  changeTab (oTab, nTab) {
    const index = this.list.indexOf(oTab)
    this.list.splice(index, 1, nTab)
    this.topTab(nTab)
  }

  removeTab (Tab) {
    const index = this.list.indexOf(Tab)
    if (index > -1) {
      const zIndex = Tab.zIndex
      this.list.forEach(item => {
        if (item.zIndex > zIndex) {
          item.zIndex--
        }
      })
      maxZIndex--
      this.list.splice(index, 1)
    }
    this.restoreTabs()
  }

  findTabByPid (pid) {
    for (let i = 0; i < this.list.length; i++) {
      let item = this.list[i]
      if (item.pid === pid) {
        return this.list[i]
      }
    }
    return null
  }

  removeTabByPid (pid) {
    let item = this.findTabByPid(pid)
    if (item !== null) {
      this.removeTab(item)
    }
  }

  topTab (Tab) {
    if (this.isExist(Tab)) {
      const zIndex = Tab.zIndex
      for (let i = 0; i < this.list.length; i++) {
        let item = this.list[i]
        if (item.zIndex > zIndex) {
          item.zIndex--
        }
      }
      Tab.zIndex = maxZIndex
      Tab.status = 'active'
      this.restoreTabs()
    }
  }

  topTabByPid (pid) {
    let item = this.findTabByPid(pid)
    if (item !== null) {
      this.topTab(item)
    }
  }

  hideTab (Tab) {
    if (this.isExist(Tab)) {
      this.list.forEach(i => {
        if (i.zIndex < Tab.zIndex) {
          i.zIndex++
        }
      })
      Tab.zIndex = 1
      Tab.status = 'hide'
      this.restoreTabs()
    }
  }

  showTab (Tab) {
    this.topTab(Tab)
  }

  clearAll () {
    this.list.splice(0, this.list.length)
  }
}
